function changePosition(){

    var content = document.getElementById("content");

    var left = content.offsetLeft;

    var top = document.body.scrollTop ;

    var bread = document.getElementById("bread");

    if( left > 230 ){

        bread.style["display"] = "block";

    }else{

        bread.style["display"] = "none";
    }

    left -= bread.offsetWidth + 20;

    if( top > 250 ){

        bread.style["position"] = "fixed" ;

        bread.style["top"] = 36 + "px" ;

        bread.style["left"] = left + "px" ;

    }else {

        bread.style["position"] = "absolute" ;

        bread.style["top"] = 286 + "px" ;

        bread.style["left"] = left + "px" ;
    }
}


function addAnchor(){

    var posArray = [];

    var ans =  document.getElementsByClassName( "anchor" );

    var bread = document.getElementById( "bread" );

    for(var i =0 ;i<ans.length;i++){

        var oDiv = document.createElement( "div" );

        var text = ans[i].getAttribute("data-title") || "未定义";

        oDiv.innerHTML = "<a>" + text + "</a>";

        oDiv.setAttribute( "data-scroll", ans[i].offsetTop );

        posArray.push( { pos : ans[i].offsetTop , elem : oDiv } );

        oDiv.onclick = function()
        {
            $( this).addClass("current").siblings().removeClass("current");

            $("html,body").stop().animate({ scrollTop : ( ( this.getAttribute("data-scroll") || 0 ) - 28 ) < 0 ? 0 : ( this.getAttribute("data-scroll") || 0 ) - 28  }, 400);
        }

        if( i == ans.length - 1 )
        {
            oDiv.style.border = 0;
        }

        bread.appendChild( oDiv );

        if( i == 0 )
        {
            oDiv.onclick();
        }
    }

    return posArray;
}

function scrollHandle( posArray )
{
    var itop = document.body.scrollTop || document.documentElement.scrollTop;

    for( var i = 0, len = posArray.length; i < len; i += 1 )
    {
        var min = posArray[ i ].pos;

        var max = posArray[ i + 1 ] ? posArray[ i + 1 ].pos : itop + 10 ;

        if( itop >= min && itop <= max )
        {
            $(  posArray[ i ].elem ).addClass("current").siblings().removeClass("current");

            break;
        }

    }
}


window.onload = function()
{
    changePosition();

    var posArray = addAnchor();

    window.onscroll = function(){
        changePosition();

        scrollHandle( posArray );

    };
    window.onresize = function(){
        changePosition();
    };
}

